
package com.rt.appauthorize;

import com.rt.schedulenew.utils.coder.DefaultSecurityCoderUtil;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;
import java.text.SimpleDateFormat;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

import com.rt.schedulenew.utils.global.ErrorCode;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.global.JsonResult;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

@Controller
@RequestMapping({"rtAuth"})
public class AppAuthController {
    private Logger log = LoggerFactory.getLogger(AppAuthController.class);
    @Autowired(required = false)
    AppAuthProperties appAuthProperties;
    @Autowired(required = false)
    AppAuthInterceptor appAuthInterceptor;

    @RequestMapping({"hasAuth"})
    @ResponseBody
    public JsonResult hasAppAuth(HttpServletRequest request) {
        String authFileDir = appAuthProperties.getFiledir();
        if (authFileDir == null || "".equals(authFileDir)) {
            authFileDir = AppAuthPathUtil.getAppJarPath() + "config/";
        }
        authFileDir = AppAuthPathUtil.dirPathFormate(authFileDir);
        Map<String, Object> map = appAuthInterceptor.verifyAuthFile(authFileDir);
        if (Boolean.parseBoolean(map.get("isValid").toString())) {
            return JsonResultUtil.success();
        }
        String rtAuthUrl = request.getContextPath().concat("/rtAuth/index");
        JsonResult jsonResult = JsonResultUtil.failure(ErrorCode.SECURITY_NO_PASS.getKey(), ErrorCode.SECURITY_NO_PASS.getValue(), rtAuthUrl);
        return jsonResult;
    }

    @RequestMapping({"index"})
    public void toAppAuthIndex(HttpServletResponse response) throws IOException {
        String authHtmlPath = "http/html/authorize.html";
        returnResourceFile(authHtmlPath, response);
    }

    @GetMapping({"getMachineCode"})
    @ResponseBody
    public JsonResult getMachineCode() {
        String key = AppAuthSerialNumberUtil.getMachineCodeSimple();
        return JsonResultUtil.success(ErrorCode.SUCCESS.getValue(), key);
    }

    @RequestMapping({"/add"})
    @ResponseBody
    public JsonResult auth(@RequestParam String authCode) {
        JsonResult result = new JsonResult();
        try {
            authCode = DefaultSecurityCoderUtil.decryptAES(authCode);
        } catch (RuntimeException e) {
            result.setStatus(ErrorCode.SECURITY_NO_PASS.getKey());
            result.setMessage("授权码格式错误或机器码不对应");
            return result;
        }
        String key = AppAuthSerialNumberUtil.getMachineCodeSimple();
        String[] parms = authCode.split(";");
        if (parms.length != 2 || !key.equals(parms[0])) {
            result.setStatus(ErrorCode.SECURITY_NO_PASS.getKey());
            result.setMessage("授权码格式错误或机器码不对应");
            return result;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String createTime = sdf.format(new Date());
        StringBuffer code = new StringBuffer();
        code.append(parms[0]).append(";").append(createTime).append(";").append(parms[1]);
        String encryptCode = DefaultSecurityCoderUtil.encryptAES(code.toString());
        String authFileDir = appAuthProperties.getFiledir();
        if (authFileDir == null || "".equals(authFileDir)) {
            authFileDir = AppAuthPathUtil.getAppJarPath() + "config/";
        }
        authFileDir = AppAuthPathUtil.dirPathFormate(authFileDir);
        File dir = new File(authFileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(authFileDir + "auth.txt");
        if (file.exists()) {
            log.warn("授权文件已存在，更新授权文件！授权文件路径：{}", authFileDir + "auth.txt");
        }
        try {
            AppAuthFileUtil.writeToFile1(file, encryptCode);
        } catch (IOException e2) {
            log.error("授权码写入到文件失败，请检查目录，路径：{}", file.getAbsolutePath());
            return JsonResultUtil.failure("授权失败！");
        }
        AppAuthInterceptor.setMachineCode(key);
        log.warn("授权成功！授权文件路径：{}", authFileDir + "auth.txt");
        return JsonResultUtil.success("授权成功");
    }

    private void returnResourceFile(String filePath, HttpServletResponse response) throws IOException {
        if (filePath.endsWith(".html")) {
            response.setContentType("text/html; charset=utf-8");
        }
        if (filePath.endsWith(".jpg")) {
            byte[] bytes = AppAuthFileUtil.readByteArrayFromResource(filePath);
            if (bytes != null) {
                response.getOutputStream().write(bytes);
            }
            return;
        }
        String text = AppAuthFileUtil.readFromResource(filePath);
        if (filePath.endsWith(".css")) {
            response.setContentType("text/css;charset=utf-8");
        } else if (filePath.endsWith(".js")) {
            response.setContentType("text/javascript;charset=utf-8");
        }
        response.getWriter().write(text);
    }

}
